import com.sun.javafx.scene.control.skin.VirtualFlow;

import java.util.*;

public class AST {
    public Node root;
    public LinkedList<Node> S;
    public int flags[] = new int[64];

    public AST(Node x){
        root = x;
        S = new LinkedList<Node>();
    }

    public void gotoHLVFL(){
        Node x;
        ListIterator<Node> it;
        x=S.peek();
        while(x.type!=NodeType.terminal) {
            visit(x);
            it = x.child.listIterator();
            while (it.hasNext()) it.next();
            while (it.hasPrevious()) {
                S.push(it.previous());
            }
            x=S.peek();
        }
    }

    public void travPost(Node x){
        if(x!=null) S.push(x);
        while (!S.isEmpty()){
            if(!S.peek().equals(x.parent)) gotoHLVFL();
            x = S.pop();
            visit(x);
        }
    }
    public void visit(Node x){
        if(x.parent!=null)
            if(x.equals(x.parent.child.peekLast())) flags[x.parent.level] = 0;

        if(x.type==NodeType.terminal) {
            x.flag = visitFlag.finished;
            flags[x.level]=0;
            print(x);
        } else if( x.child.size()>1){
            if(x.flag==visitFlag.unvisited) {
                x.flag = visitFlag.visited;
                flags[x.level] = 1;
                print(x);
            } else{
                x.flag = visitFlag.finished;
                flags[x.level] = 0;
            }
        } else {
            if(x.flag == visitFlag.unvisited){
                x.flag = visitFlag.visited;
                print(x);
            } else if(x.flag == visitFlag.visited) {
                x.flag=visitFlag.finished;
                flags[x.level]=0;
            }
        }
    }

    public void print(Node x) {
        if(x.level==0) {
            System.out.print("'"+x.text+"'\n");
            return;
        }
        for(int i = 0;i<x.level-1;i++){
            if(flags[i]==1) {
                System.out.print(" |\t ");
            } else {
                System.out.print(" \t ");
            }
        }
        System.out.print(" |--- '"+x.text+"'\n");
    }

}
